import type { UserModelState } from '@/models/userModel';
import { login, phoneLoginS, sendVerifyCode } from '@/services/home/api';
import { getWXQRCode, qqLogin, weixinLogin } from '@/services/user';
import {
  LoadingOutlined,
  LockOutlined,
  MobileOutlined,
  QqCircleFilled,
  UserOutlined,
} from '@ant-design/icons';
import { CaptFieldRef, LoginForm, ProFormCaptcha, ProFormInstance, ProFormText } from '@ant-design/pro-components';
import type { ConnectRC } from '@umijs/max';
import { connect, useModel, useRequest } from '@umijs/max';
import { Button, message, Modal, Tabs } from 'antd';
import createPuzzle from 'create-puzzle';
import { QRCodeCanvas } from 'qrcode.react';
import SliderCaptcha from 'rc-slider-captcha';
import { forwardRef, useEffect, useImperativeHandle, useRef, useState } from 'react';

import Register from '../Register';
import styles from './index.less';
type LoginType = 'weixin' | 'account' | 'register' | 'phone';

interface Props {
  refInstance: any;
  usermodel: UserModelState;
}

const Index: ConnectRC<Props> = (props) => {
  const {
    refInstance,
    usermodel: { isShowLoginModal },
    dispatch,
  } = props;
  const { initialState, setInitialState, refresh } = useModel('@@initialState');
  const [loginType, setLoginType] = useState<LoginType>('phone');
  const [QRCodeUrl, setQRCodeUrl] = useState<string>('');
  const [isValidated, setIsValidated] = useState<boolean>(false);

  const formRef = useRef<ProFormInstance>();
  const offsetXRef = useRef(0); // x 轴偏移值
  const captchaRef = useRef<CaptFieldRef | null | undefined>();

  const { run: weixinLoginRun, cancel } = useRequest(weixinLogin, {
    manual: true,
    pollingInterval: 5000,
    onSuccess: async (result: string) => {
      if (result) {
        const tokenObj = localStorage.getItem(BASE_TOKEN_NAME) || '{}';
        const newTokenObj = JSON.parse(tokenObj);
        newTokenObj.access_token = result;
        await initialState?.fetchUserInfo?.();
        dispatch({ type: 'usermodel/changeIsShowLoginModal', payload: false });
      }
      cancel();
    },
  });
  const { loading, run } = useRequest(getWXQRCode, {
    manual: true,
    onSuccess: (result: COMMON.QrCodeType) => {
      setQRCodeUrl(result.qrCodeReturnUrl);
      weixinLoginRun(result.tempUserId);
    },
  });
  // 登录
  const loginHandler = async (e: HOMEAPI.LoginForm | HOMEAPI.PhoneLoginT) => {
    // e.password = aesEncryption(e.password || ''); // 加密
    const {
      data: resData,
      code: resCode,
      message: resMsg,
    } = loginType === 'account' ? await login(e) : await phoneLoginS(e as HOMEAPI.PhoneLoginT);
    if (resCode !== 200) {
      message.error(resMsg);
      return true;
    }
    // token过期时间
    resData.tokenSurvivalTime = Date.now() + resData.expires_in * 1000;
    // 缓存到本地
    localStorage.setItem(BASE_TOKEN_NAME, JSON.stringify(resData));
    // 获取用户信息
    const {
      code,
      message: messageText,
      data,
    } = (await initialState?.fetchUserInfo?.(
      'login',
    )) as unknown as COMMON.BaseSuccess<HOMEAPI.CurrentUser>;
    if (code === 200) {
      message.success('登录成功!');
      await setInitialState((s: any) => ({
        ...s,
        currentUser: data,
      }));
      refresh();
      dispatch({ type: 'usermodel/changeIsShowLoginModal', payload: false });
    } else {
      message.error(messageText);
    }
    return true;
  };

  const qqClick = async () => {
    const res = await qqLogin();
    localStorage.setItem('processMode', 'qqlogin');
    window.open(res.data);
  };

  const getCode = async () => {
    const mobile = formRef.current?.getFieldValue('mobile')
    const { code, message: msg } = await sendVerifyCode(mobile);
    if (code === 200) {
      message.success('获取验证码成功!');
    } else {
      message.error(msg);
    }
  };

  useEffect(() => {
    if (loginType === 'weixin') {
      run();
    }
  }, [loginType]);

  useEffect(() => {
    window.showLoginModal = (param: boolean) => {
      dispatch({ type: 'usermodel/changeIsShowLoginModal', payload: param });
    };
  }, []);

  useImperativeHandle(refInstance, () => ({}));
  return (
    <div>
      <Modal
        open={isShowLoginModal}
        onCancel={() => dispatch({ type: 'usermodel/changeIsShowLoginModal', payload: false })}
        footer={null}
        title={<div style={{ textAlign: 'center' }}>登录</div>}
      >
        <div className={styles.wrapper}>
          <LoginForm
            onFinish={loginHandler}
            isKeyPressSubmit
            submitter={false}
            formRef={formRef}
            actions={
              <div className={styles.actions}>
                <div className={styles.otherLoginType}>
                  <span>其它登录方式:</span>
                  <QqCircleFilled
                    onClick={qqClick}
                    style={{ color: '#1677FF', fontSize: '26px' }}
                  />
                </div>
                <div>
                  注册登录即表示同意
                  <a onClick={() => window.open(`/agreement/view/1`)}> 网站使用条款 </a>和
                  <a onClick={() => window.open(`/agreement/view/2`)}> 隐私政策 </a>
                </div>
              </div>
            }
          >
            <Tabs
              centered
              activeKey={loginType}
              onChange={(activeKey) => setLoginType(activeKey as LoginType)}
              items={[
                { key: 'phone', label: '免密登录' },
                { key: 'account', label: '密码登录' },
                // { key: 'weixin', label: '微信登录' },
              ]}
            />
            {loginType === 'account' && (
              <>
                <ProFormText
                  name="username"
                  fieldProps={{
                    size: 'large',
                    prefix: <UserOutlined className={'prefixIcon'} />,
                  }}
                  placeholder={'手机号/邮箱/用户名'}
                  rules={[
                    {
                      required: true,
                      message: '请输入用户名!',
                    },
                  ]}
                />
                <ProFormText.Password
                  name="password"
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={'prefixIcon'} />,
                  }}
                  placeholder={'密码'}
                  rules={[
                    {
                      required: true,
                      message: '请输入密码！',
                    },
                  ]}
                />
                <Button block htmlType="submit" type="primary">
                  登录
                </Button>
                {/* <div
                  style={{
                    marginBlockEnd: 24,
                  }}
                >
                  <a
                    style={{
                      float: 'right',
                    }}
                    onClick={() =>
                      dispatch({ type: 'usermodel/changeIsRegisterModal', payload: true })
                    }
                  >
                    去注册
                  </a>
                </div> */}
              </>
            )}
            {loginType === 'phone' && (
              <>
                <ProFormText
                  fieldProps={{
                    size: 'large',
                    prefix: <MobileOutlined className={'prefixIcon'} />,
                  }}
                  name="mobile"
                  placeholder={'手机号'}
                  rules={[
                    {
                      required: true,
                      message: '请输入手机号！',
                    },
                    {
                      pattern: /^1\d{10}$/,
                      message: '手机号格式错误！',
                    },
                  ]}
                />
                <ProFormCaptcha
                  fieldProps={{
                    size: 'large',
                    prefix: <LockOutlined className={'prefixIcon'} />,
                  }}
                  phoneName="mobile"
                  captchaProps={{
                    size: 'large',
                  }}
                  placeholder={'请输入验证码'}
                  name="code"
                  rules={[
                    {
                      required: true,
                      message: '请输入验证码！',
                    },
                  ]}
                  fieldRef={captchaRef}
                  onGetCaptcha={async () => {
                    if (!offsetXRef.current) {
                      setIsValidated(true);
                      return new Promise((resolve, reject) => {
                        reject();
                      });
                    }
                  }}
                />
                <Button block htmlType="submit" type="primary">
                  登录/注册
                </Button>
              </>
            )}
            {loginType === 'weixin' && (
              <div className={styles.qrCodeWrapper}>
                {loading ? <LoadingOutlined /> : <QRCodeCanvas value={QRCodeUrl} />}
              </div>
            )}
          </LoginForm>
        </div>
      </Modal>
      <Modal
        open={isValidated}
        onCancel={() =>{
          offsetXRef.current = 0;
          setIsValidated(false)
        }}
        title="安全验证"
        footer={false}
        centered
        width={400}
        style={{ maxWidth: '100%' }}
      >
        <SliderCaptcha
          request={() => {
            return createPuzzle('https://picsum.photos/360/260').then((res: any) => {
              offsetXRef.current = res.x;
              return {
                bgUrl: res.bgUrl,
                puzzleUrl: res.puzzleUrl,
              };
            });
          }}
          onVerify={async (data) => {
            if (data.x >= offsetXRef.current - 5 && data.x < offsetXRef.current + 5) {
              setTimeout(() => {
                setIsValidated(false);
                offsetXRef.current = 1;
                captchaRef.current?.startTiming();
                getCode();
              }, 1000);
              return Promise.resolve();
            }
            offsetXRef.current = 0;
            return Promise.reject();
          }}
          bgSize={{
            width: 360,
          }}
          loadingDelay={300}
        />
      </Modal>
      <Register />
    </div>
  );
};
export default connect(({ usermodel }: { usermodel: UserModelState }) => ({
  usermodel,
}))(forwardRef((props: any, ref) => <Index {...props} refInstance={ref} />));
